
package com.jf.cloud.user.feign;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.jf.cloud.api.user.bo.UidAndUserIdBO;
import com.jf.cloud.api.user.dto.MemberReqDTO;
import com.jf.cloud.api.user.dto.UserRegisterDTO;
import com.jf.cloud.api.user.feign.UserFeignClient;
import com.jf.cloud.api.user.vo.MemberContributeRespVO;
import com.jf.cloud.api.user.vo.MemberContributeValueVO;
import com.jf.cloud.api.user.vo.MemberOverviewVO;
import com.jf.cloud.api.user.vo.UserApiVO;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.util.DateUtils;
import com.jf.cloud.user.mapper.UserBalanceLogMapper;
import com.jf.cloud.user.mapper.UserExtensionMapper;
import com.jf.cloud.user.mapper.UserMapper;
import com.jf.cloud.user.service.UserRechargeCouponService;
import com.jf.cloud.user.service.UserRightsService;
import com.jf.cloud.user.service.UserService;
import com.jf.cloud.user.vo.UserExtensionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.v3.oas.annotations.Hidden;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户地址feign连接
 * @author zz
 * @date 2020/12/07
 */
@RestController
@Hidden
public class UserFeignController implements UserFeignClient {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private UserExtensionMapper userExtensionMapper;
    @Autowired
    private UserBalanceLogMapper userBalanceLogMapper;
    @Autowired
    private UserRightsService userRightsService;
    @Autowired
    private UserRechargeCouponService userRechargeCouponService;

    @Override
    public ServerResponseEntity<List<UserApiVO>> getUserByUserIds(List<Long> userIds) {
        List<UserApiVO> userList = userService.getUserByUserIds(userIds);
        return ServerResponseEntity.success(userList);
    }

    @Override
    public ServerResponseEntity<List<UserApiVO>> getUserByParam(UserApiVO userApiVO) {
        return  ServerResponseEntity.success(userService.getUserByParam(userApiVO));
    }

    @Override
    public ServerResponseEntity<UserApiVO> getUserData(Long userId) {
        UserApiVO user = userService.getByUserId(userId);
        return ServerResponseEntity.success(user);
    }

    @Override
    public ServerResponseEntity<UserApiVO> getInsiderUserData(Long userId) {
        UserApiVO user = userService.getByUserId(userId);
        return ServerResponseEntity.success(user);
    }

    @Override
    public ServerResponseEntity<MemberOverviewVO> getUserAnalysis(MemberReqDTO param, Date startTime, Date endTime) {
        MemberOverviewVO res = new MemberOverviewVO();
        // 累积会员数
        param.setDateTime(endTime);
        res.setCurrentDay(DateUtils.dateToNumber(startTime));
        res.setTotalMember(userExtensionMapper.countMemberByParam(param));
        // 新增会员数
        param.setDateTime(startTime);
        Integer preAccumulate = userExtensionMapper.countMemberByParam(param);
        res.setNewMember(res.getTotalMember() - preAccumulate);
        // 筛选时间内，购买商品的会员人数
        param.setDateTime(null);
        param.setStartTime(startTime);
        param.setEndTime(endTime);
        if (param.getMemberType() != 0){
            //如果查询类型不是全部会员则需要过滤
            res.setUserIds(getMeetConditionsUserIds(param).getData());
        }else {
            res.setUserIds(param.getUserIds());
        }
        // 获取储值会员数
        res.setStoredValue(userBalanceLogMapper.countByConditions(param));
        return ServerResponseEntity.success(res);
    }

    @Override
    public ServerResponseEntity<MemberOverviewVO> getMemberAnalysisByParam(MemberReqDTO param) {
        // 累积会员数和新增会员数
        MemberOverviewVO res = userExtensionMapper.countMemberDataByParam(param);
        //不查全部会员信息就过滤
        if (param.getMemberType() != 0){
            // 筛选时间内，购买商品的会员人数,先获取当前符合条件的会员数(只是查询一天的应该数据量不会很大？)
            res.setUserIds(getMeetConditionsUserIds(param).getData());
        }else {
            res.setUserIds(param.getUserIds());
        }
        return ServerResponseEntity.success(res);
    }

    @Override
    public ServerResponseEntity<List<Long>> getMeetConditionsUserIds(MemberReqDTO param) {
        if(CollectionUtil.isEmpty(param.getUserIds())){
            return ServerResponseEntity.success(null);
        }
        // 根据用户id，获取用户的信息
        List<UserExtensionVO> userExtensionList = userExtensionMapper.countByMemberTypeConditions(param);
        List<Long> userIds = new ArrayList<>();
        // 根据用户等级进行分类
        Map<Integer, List<UserExtensionVO>> userInfoMap = userExtensionList.stream().collect(Collectors.groupingBy(UserExtensionVO::getLevelType));
        // 查找指定等级的用户时，过滤多余的数据
        if (!Objects.equals(param.getMemberType(), 0) && userInfoMap.containsKey(param.getMemberType() - 1)) {
            userExtensionList = userInfoMap.get(param.getMemberType()  - 1);
        }else if (param.getMemberType() != 0){
            //查询类型不为全部全员,上面过滤不执行则清空全部
            userExtensionList = null;
        }

        if (CollectionUtil.isNotEmpty(userExtensionList)) {
            userExtensionList.forEach(userExtensionVO -> userIds.add(userExtensionVO.getUserId()));
        }
        return ServerResponseEntity.success(userIds);
    }

    @Override
    public ServerResponseEntity<MemberContributeRespVO> getMemberContributeByParam(MemberReqDTO param) {
        Date endTime = param.getEndTime();
        param.setDateTime(endTime);
        // 先获取当前符合条件的所有会员数(只是查询一天的应该数据量不会很大？)
        List<UserExtensionVO> userExtensionList = userExtensionMapper.countByMemberTypeConditions(param);
        List<Long> userIds = new ArrayList<>();
        Map<Integer, List<UserExtensionVO>> userInfoMap = userExtensionList.stream().collect(Collectors.groupingBy(UserExtensionVO::getLevelType));

        MemberContributeRespVO respParam = new MemberContributeRespVO();
        // 普通会员
        MemberContributeValueVO publicMember = new MemberContributeValueVO();
        // 付费会员
        MemberContributeValueVO paidMember = new MemberContributeValueVO();

        // 普通会员
        param.setMemberType(1);
        publicMember.setTotalMember(userExtensionMapper.countMemberByParam(param));
        // 普通会员ids
        List<UserExtensionVO> memberList = userInfoMap.get(0);
        for (UserExtensionVO extensionVO : memberList) {
            userIds.add(extensionVO.getUserId());
        }
        respParam.setUserIds(userIds);
        // 付费会员
        param.setMemberType(2);
        param.setDateTime(endTime);
        paidMember.setTotalMember(userExtensionMapper.countMemberByParam(param));
        respParam.setPublicMember(publicMember);
        respParam.setPaidMember(paidMember);
        // 付费会员ids
        userIds = new ArrayList<>();
        memberList = userInfoMap.get(1);
        if (Objects.nonNull(memberList) && memberList.size() > 0){
            for (UserExtensionVO userExtensionVO : memberList) {
                userIds.add(userExtensionVO.getUserId());
            }
        }
        respParam.setPaidUserIds(userIds);
        return ServerResponseEntity.success(respParam);
    }

    @Override
    public ServerResponseEntity<Integer> getMemberTrend(MemberReqDTO param) {
        return ServerResponseEntity.success(userExtensionMapper.countMemberByParam(param));
    }

    @Override
    public ServerResponseEntity<Integer> countUserByMobile(String mobile) {
        return ServerResponseEntity.success(userService.countUserByMobile(mobile));
    }

    @Override
    public ServerResponseEntity<Void> cancelBindingCoupons(List<Long> couponIds) {
        if (CollUtil.isNotEmpty(couponIds)) {
            userRechargeCouponService.cancelBindingCoupons(couponIds);
            userRightsService.cancelBindingCoupons(couponIds);
        }
        return ServerResponseEntity.success();
    }

    @Override
    public ServerResponseEntity<UserApiVO> getUserAndOpenIdsByUserId(Long userId) {
        return ServerResponseEntity.success(userService.getUserAndOpenIdsByUserId(userId));
    }

    @Override
    public ServerResponseEntity<List<Long>> getUserIdListByLevel(Integer level) {
        return ServerResponseEntity.success(userService.getUserIdListByLevel(level));
    }

    @Override
    public ServerResponseEntity<UidAndUserIdBO> save(UserRegisterDTO userRegisterDTO) {
        return ServerResponseEntity.success(userService.save(userRegisterDTO.getMobile(),null,userRegisterDTO.getTempUid()));
    }


}
